package cn.shenzz.suixiang.link.leetcode_19;

import cn.shenzz.suixiang.link.ListNode;

import static cn.shenzz.suixiang.link.ListNode.printList;

class Solution {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);

        Solution solution = new Solution();

        ListNode result1 = solution.removeNthFromEnd(head, 2);
        printList(result1);
    }

    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(-1, head);
        ListNode slow = dummy, fast = dummy;
        int digit = 0;
        while (digit++ < n) {
            fast = fast.next;
        }
        while (fast.next != null) {
            slow = slow.next;
            fast = fast.next;
        }
        slow.next = slow.next.next;
        return dummy.next;
    }
}